<script setup lang="ts">
import Layouts from './components/layouts/index.vue'
import Presets from './components/presets/index.vue'
import { getRenderingEngine } from '@cornerstonejs/core';
import * as cornerstoneTools from '@roos/cornerstone3d-tools';
import { RenderingEngineId } from '@/views/dcm-view/assets/constant';
const {
    Enums: csToolsEnums,
    PlanarRotateTool,
    ReferenceLinesTool,
    ScaleOverlayTool,
    ArrowAnnotateTool,
    PanTool,
    ZoomTool,
    StackScrollMouseWheelTool,
    WindowLevelTool,
    LengthTool,
    HeightTool,
    AngleTool,
    CobbAngleTool,
    BidirectionalTool,
    ProbeTool,
    RectangleROITool,
    EraserTool,
    MagnifyTool,
    OrientationMarkerTool,
    CardiothoracicRatioTool,
    TrackballRotateTool,
    annotation,
    utilities
} = cornerstoneTools;
const { state } = annotation
const { getAnnotationNearPoint } = utilities
import { clearGeneralToolState, setToolActive, giveUp, isCornerstoneTool } from '@/views/dcm-view/assets/toolFactory'
/*========================================>( 模板属性 )<========================================*/
//当前活跃的toolColumnIndex
const activeTitleIndex = ref<number>(1)
//toolPad是否可见
const isShow = ref<boolean>(true)
//目前活跃的Tool
const activeToolMark = ref()
const activeCacheMarks = ref<Array<string>>([])
//是否显示布局选择面板
const showLayouts = ref<boolean>()
//是否显示预设窗宽窗位
const showPresets = ref<boolean>()

const props = defineProps(['toolGroup', 'moveEvent'])

const route = useRoute();

/*========================================>( 作用域属性 )<========================================*/
const _menus = [
    {
        title: '文件',
        icon: 'folder',
        groups: [
            {
                title: undefined,
                btnMenuList: [
                    {
                        title: '导入图像',
                        mark: 'f1',
                        icon: 'import',

                    },
                    {
                        title: '定位目录',
                        mark: 'f2',
                        icon: 'export'
                    }
                ]
            },
            {
                title: '缓存',
                btnMenuList: [
                    {
                        title: '清除缓存',
                        mark: 'f3',
                        icon: 'clear'
                    }
                ]
            }
        ]
    },
    {
        title: '常用',
        icon: 'toolbox',
        groups: [
            {
                title: "布局",
                btnMenuList: [
                    {
                        title: '序列',
                        mark: 't1',
                        icon: 'layout'
                    }
                ]
            },
            {
                title: "浏览",
                btnMenuList: [
                    {
                        title: '浏览',
                        mark: 's1',
                        icon: 'com-show'
                    },
                    {
                        title: '重置',
                        mark: 's4',
                        icon: 'reset'
                    }
                ]
            },
            {
                title: "灰度",
                btnMenuList: [
                    {
                        title: '窗宽窗位',
                        mark: 'WindowLevel',
                        icon: 'window-center'
                    },
                    {
                        title: '预设',
                        mark: 't2',
                        icon: 'color'
                    },
                    {
                        title: '反色',
                        mark: 't3',
                        icon: 'inverse'
                    }
                ]
            },
            {
                title: "图像操作",
                btnMenuList: [
                    {
                        title: '自由旋转',
                        mark: 'PlanarRotate',
                        icon: 'rotate'
                    },
                    {
                        title: '旋转90°',
                        mark: 't4',
                        icon: 'rotate90'
                    },
                    {
                        title: '垂直镜像',
                        mark: 't5',
                        icon: 'mirror'
                    },
                    {
                        title: '水平镜像',
                        mark: 't6',
                        icon: 'mirror'
                    }
                ]
            },
            {
                title: "标注测量",
                btnMenuList: [
                    {
                        title: '文字',
                        mark: 'ArrowAnnotate',
                        icon: 'font'
                    },
                    {
                        title: '长度',
                        mark: 'Length',
                        icon: 'rule'
                    },
                    {
                        title: '心胸比',
                        mark: 'CardiothoracicRatio',
                        icon: 'heart'
                    },
                    {
                        title: 'HU值',
                        mark: 'Probe',
                        icon: 'posi'
                    },
                    {
                        title: '清除标注',
                        mark: 'ff1',
                        icon: 'clear'
                    }
                ]
            },
            {
                title: "3D",
                btnMenuList: [
                    {
                        title: '3D视图',
                        mark: 't9',
                        icon: 'view3d'
                    }
                ]
            },
            {
                title: "报告",
                btnMenuList: [
                    {
                        title: '查看报告',
                        mark: 't10',
                        icon: 'report'
                    }
                ]
            },
            {
                title: "其他",
                btnMenuList: [
                    {
                        title: '快捷键',
                        mark: 't11',
                        icon: 'hotkey'
                    },
                    {
                        title: '全屏浏览',
                        mark: 't12',
                        icon: 'full-screen'
                    }
                ]
            }
        ]
    },
    {
        title: '浏览',
        icon: 'eyes',
        groups: [
            {
                title: "浏览操作",
                btnMenuList: [
                    {
                        title: '浏览',
                        mark: 's1',
                        icon: 'com-show'
                    },
                    {
                        title: '放大镜',
                        mark: 'Magnify',
                        icon: 'magnify'
                    }
                ]
            },
            {
                title: "图像大小",
                btnMenuList: [
                    {
                        title: '适应窗口',
                        mark: 's5',
                        icon: 'original-drawing'
                    },
                    {
                        title: '实际大小',
                        mark: 's6',
                        icon: 'square'
                    }
                ]
            },
            {
                title: "自动播放",
                btnMenuList: [
                    {
                        title: '开始',
                        mark: 's8',
                        icon: 'play'
                    },
                    {
                        title: '停止',
                        mark: 's9',
                        icon: 'stop'
                    },
                    {
                        title: '上一帧',
                        mark: 's10',
                        icon: 'pre'
                    },
                    {
                        title: '下一帧',
                        mark: 's11',
                        icon: 'next'
                    },
                    {
                        title: '全部停止',
                        mark: 's12',
                        icon: 'stop-all'
                    },
                ]
            },
            {
                title: "信息",
                btnMenuList: [
                    {
                        title: 'DICOM',
                        mark: 's13',
                        icon: 'info'
                    }
                ]
            }
        ]
    },
    {
        title: '标注测量',
        icon: 'measure',
        groups: [
            {
                title: "标注工具",
                btnMenuList: [
                    {
                        title: '浏览',
                        mark: 's1',
                        icon: 'com-show'
                    },
                    {
                        title: '文字',
                        mark: 'ArrowAnnotate',
                        icon: 'font'
                    },
                    // {
                    //     title: '方形',
                    //     mark: 'RectangleScissor',
                    //     tool: true,
                    //     cache: true,
                    //     icon: 'square'
                    // },
                    // {
                    //     title: '椭圆',
                    //     mark: '',
                    //     tool: true,
                    //     cache: true,
                    //     icon: 'ellip'
                    // },
                    // {
                    //     title: '自由区域',
                    //     mark: '',
                    //     tool: true,
                    //     cache: true,
                    //     icon: 'free-select'
                    // }
                ]
            },
            {
                title: "测量工具",
                btnMenuList: [
                    {
                        title: '长度',
                        mark: 'Length',
                        icon: 'rule'
                    },
                    {
                        title: '高度',
                        mark: 'Height',
                        icon: 'height'
                    },
                    {
                        title: '角度',
                        mark: 'Angle',
                        icon: 'angle'
                    },
                    {
                        title: 'Cobb角',
                        mark: 'CobbAngle',
                        icon: 'cobb'
                    },
                    {
                        title: '双向长宽',
                        mark: 'Bidirectional',
                        icon: 'inverse'
                    },
                    {
                        title: '心胸比',
                        mark: 'CardiothoracicRatio',
                        icon: 'heart'
                    },
                    {
                        title: 'HU值',
                        mark: 'Probe',
                        icon: 'posi'
                    },
                    {
                        title: '方形HU值',
                        mark: 'RectangleROI',
                        icon: 'square-hu'
                    },
                ]
            },
            {
                title: "删除",
                btnMenuList: [
                    {
                        title: '橡皮擦',
                        mark: 'Eraser',
                        icon: 'eraser'
                    },
                    {
                        title: '全部删除',
                        mark: 'ff1',
                        icon: 'delete-all'
                    }
                ]
            },

        ]
    }
]

/*========================================>( dom属性 )<========================================*/
const domLayouts = ref()
const domPresets = ref()

/*========================================>( 子传父方法 )<========================================*/
const emits = defineEmits(['back'])

/*========================================>( 普通方法 )<========================================*/
//调取基石工具
const doCtn = (toolName: string) => {
    console.log('调取基石方法：' + toolName)
    setToolActive(props.toolGroup, toolName)
}

//调取普通函数
const doNormal = (mark: string) => {
    switch (mark) {
        case 't1':
            //选择布局
            showLayouts.value = true
            nextTick(() => {
                onClickOutside(domLayouts, event => showLayouts.value = false)
            })
            return
        case 't2':
            showPresets.value = true
            nextTick(() => {
                onClickOutside(domPresets, event => showPresets.value = false)
            })
            return
        case 't10':
            //去往报告
            var styId = Array.isArray(route.params.styId) ? route.params.styId[0] : route.params.styId
            window.open("/ris/report/" + styId)
            break
        case 't12':
            //全屏浏览
            handleFullScreenClick()
            break
        case 'ff1':
            //清除工具实例缓存
            clearGeneralToolState(props.toolGroup)
            break
        case 's1':
            //浏览：放弃工具
            giveUp(props.toolGroup)
            activeToolMark.value = undefined
            break
    }
    emits('back', {
        mark
    })
}

/*========================================>( 监听方法 )<========================================*/
//监听工具大类点击
const handleMenuTitleClick = (index: number) => {
    activeTitleIndex.value = index
}
//监听触发隐藏
const handleFullScreenClick = (status?: boolean) => {
    //全屏预览
    //触发image-selector的隐藏
    isShow.value = !isShow.value
    const event = new CustomEvent('image-selector-visiable', {});
    window.dispatchEvent(event);
}
//监听按钮点击
const handleBtnClick = (menu: any) => {
    const { mark, cache, conflict, block } = menu
    console.log('点击了按钮：' + menu.mark)
    if (isCornerstoneTool(menu.mark)) {
        //是基石工具
        activeToolMark.value = mark
        //调取工具方法
        doCtn(mark)
    } else {
        //普通按钮
        if (cache) {
            if (activeCacheMarks.value.includes(mark)) {
                if (block) {
                    return
                }
                activeCacheMarks.value = activeCacheMarks.value.filter(m => m != mark)
            } else {
                if (conflict) {
                    activeCacheMarks.value = activeCacheMarks.value.filter(m => m != conflict)
                }
                activeCacheMarks.value.push(mark)
            }
        }
        doNormal(mark)
    }
}

//监听布局改变
const handleLayoutChanged = (value: any) => {
    emits('back', {
        mark: 't1',
        value
    })
    showLayouts.value = false
}

//监听窗宽窗位变化
const handlePresetsChanged = (value: any) => {
    emits('back', {
        mark: 't2',
        value
    })
    showPresets.value = false
}

/*========================================>( 暴露方法 )<========================================*/
const hide = () => {
    isShow.value = false
}

const enableLastTool = () => {
    if (isCornerstoneTool(activeToolMark.value)) {
        setToolActive(props.toolGroup, activeToolMark.value)
    }
}

defineExpose({
    hide, enableLastTool
})

//初始化工具
cornerstoneTools.addTool(ArrowAnnotateTool);
cornerstoneTools.addTool(PanTool);
cornerstoneTools.addTool(ZoomTool);
cornerstoneTools.addTool(StackScrollMouseWheelTool);
cornerstoneTools.addTool(WindowLevelTool);
cornerstoneTools.addTool(LengthTool);
cornerstoneTools.addTool(HeightTool);
cornerstoneTools.addTool(AngleTool);
cornerstoneTools.addTool(CobbAngleTool);
cornerstoneTools.addTool(BidirectionalTool);
cornerstoneTools.addTool(ProbeTool);
cornerstoneTools.addTool(RectangleROITool);
cornerstoneTools.addTool(EraserTool);
cornerstoneTools.addTool(ScaleOverlayTool);
cornerstoneTools.addTool(ReferenceLinesTool);
cornerstoneTools.addTool(PlanarRotateTool);
cornerstoneTools.addTool(MagnifyTool);
cornerstoneTools.addTool(OrientationMarkerTool);
cornerstoneTools.addTool(CardiothoracicRatioTool);
cornerstoneTools.addTool(TrackballRotateTool);

onMounted(() => {
    //初始化快捷键
    window.onkeydown = (event) => {
        let isHotKey = true
        const { code } = event

        switch (code) {
            case 'Space':
                //空格键放弃工具
                giveUp(props.toolGroup)
                activeToolMark.value = undefined
                break
            case 'Delete':
                //删除鼠标附近工具缓存
                var ignores = ['ScaleOverlay', 'ReferenceLines']
                var coords = props.moveEvent.detail.currentPoints.canvas
                var element = props.moveEvent.detail.element
                var annotation = getAnnotationNearPoint(element, coords)
                if (!annotation) return
                var toolName = annotation.metadata.toolName
                if (ignores.includes(toolName)) return
                state.removeAnnotation(annotation.annotationUID ?? '')
                var renderingEngine = getRenderingEngine(RenderingEngineId);
                var viewports = renderingEngine?.getViewports() ?? [];
                viewports.forEach((v) => v.render());
                break
            case 'F11':
                //切换全屏
                handleFullScreenClick()
                break
            case 'F4':
                //鼓窗wwwc
                handlePresetsChanged([1600, 500])
                break
            case 'F7':
                //软组织wwwc
                handlePresetsChanged([80, 40])
                break
            default:
                isHotKey = false
                break
        }
        if (isHotKey) {
            event.stopPropagation()
            event.preventDefault()
        }
    }
})

</script>
<template>
    <div class="component-container tool-pad" :style="{ height: isShow ? '140px' : '0' }">
        <div v-show="isShow" class="title-box">
            <div v-for="item, index in _menus" :key="index" class="column"
                :class="{ active: index == activeTitleIndex }" @click="handleMenuTitleClick(index)">
                <svg-icon :icon-class="item.icon" width="23" height="23" class="p-r-0-3 p-c-5-0" />{{ item.title }}
                <div v-if="index == activeTitleIndex" class="bud"></div>
            </div>
        </div>
        <div class="menu-box">
            <div v-for="group, gindex in _menus[activeTitleIndex].groups" :key="gindex" class="menu-group">
                <div v-for="menu, mindex in group.btnMenuList" :key="mindex" class="menu" :id="'menu-' + menu.mark"
                    :class="{ active: activeToolMark == menu.mark || activeCacheMarks.includes(menu.mark) }"
                    @click="handleBtnClick(menu)">
                    <svg-icon :icon-class="menu.icon" width="30" height="30" />
                    <div class="name">{{ menu.title }}</div>
                </div>
                <div class="group-title">{{ group.title ?? _menus[activeTitleIndex].title }}</div>
            </div>
        </div>
        <div class="hidebtn" @click="handleFullScreenClick()">
            <svg-icon :icon-class="isShow ? 'to-top' : 'to-bottom'" width="20" height="20" />
        </div>
        <Layouts v-if="showLayouts" ref="domLayouts" @change="handleLayoutChanged" />
        <Presets v-if="showPresets" ref="domPresets" @change="handlePresetsChanged" />
    </div>
</template>
<style lang="scss"></style>
<style lang="scss" scoped>
.component-container.tool-pad {
    width: 100%;
    height: 140px;
    position: relative;
    box-sizing: border-box;

    .title-box {
        width: 100%;
        height: 140px;
        display: flex;
        flex-direction: row;
        box-sizing: border-box;

        .column {
            width: 150px;
            line-height: 32px;
            color: #fff;
            text-align: center;
            cursor: pointer;
            border: solid 2px rgba(0, 0, 0, 0);
            position: relative;

            &:hover {
                background-color: #333;
            }

            &.active:hover {
                background-color: #3d3d3d;
            }

            .bud {
                width: 100%;
                height: 4px;
                background-color: #4d4d4d;
                position: absolute;
                top: 33px;
                left: 0;
                z-index: 1;
            }
        }

        .column.active {
            border: solid 2px #ccc;
            color: #0099CC;
            font-weight: bold;
        }
    }

    .menu-box {
        width: 100%;
        height: 100px;
        position: absolute;
        bottom: 0;
        left: 0;
        border: solid 2px #ccc;
        background-color: #3d3d3d;
        overflow-x: auto;

        .menu-group {
            display: table;
            height: 90px;
            border-right: solid 1px #ccc;
            float: left;
            padding: 0 10px;
            margin-top: 5px;


            .group-title {
                height: 30px;
                text-align: center;
                line-height: 30px;
                color: #999;
                font-size: 15px;
            }

            .menu {
                box-sizing: border-box;
                display: table;
                min-width: 50px;
                height: 60px;
                float: left;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                cursor: pointer;
                border: solid 1px rgba(0, 0, 0, 0);

                .svg-icon {
                    color: #99CCFF;
                }

                .name {
                    color: #fff;
                    font-size: 13px;
                    padding: 0 8px;
                }

                &:hover {
                    background-color: #333;
                }

                &.active {
                    border: solid 1px #99CCFF;
                }

            }

        }


    }

    .hidebtn {
        width: 80px;
        height: 10px;
        background-color: #3d3d3d;
        position: absolute;
        bottom: -10px;
        left: 0;
        right: 0;
        margin: auto;
        border-right: solid 2px #ccc;
        border-left: solid 2px #ccc;
        border-bottom: solid 2px #ccc;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;

        &:hover {
            background-color: #4d4d4d;
        }

        .svg-icon {
            color: #ccc;
        }
    }

}
</style>